package com.example.vocab.controller;

import com.alibaba.fastjson.JSON;
import com.example.vocab.dao.HistoryDao;
import com.example.vocab.entity.Word;
import com.example.vocab.service.HistoryService;
import com.example.vocab.service.WordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@RestController
public class ResultController {

    @Resource(name="historyServiceImpl")
    HistoryService historyService;
    @Resource(name="wordServiceImpl")
    WordService wordService;

    @RequestMapping("getresult")
    public String getResult(@RequestBody HashMap<String,String[]> map,
                            @RequestParam(value="username", required=true) String username,
                            @RequestParam(value="time",required=true) String time,
                            @RequestParam(value="second",required=true) int s)
    {
        String[] widTotals = map.get("total");
        String[] wids = map.get("wid");
        List<Integer> frequencies=new ArrayList<>();
        List<Integer> totals=new ArrayList<>();
        for (String wid : wids) {
            if(wid!=null)
                frequencies.add(wordService.getFrequencyByWid(Integer.parseInt(wid)));
        }
        for (String id : widTotals) {
            if(id!=null)
                totals.add(wordService.getFrequencyByWid(Integer.parseInt(id)));
        }
        int easy=0;
        int mid=0;
        int hard=0;
        for (Integer f : frequencies) {
            if(0<f&&f<30000)
                hard++;
            else if(30000<f&&f<300000)
                mid++;
            else if(f>300000)
                easy++;
        }
        int easyTotal=0;
        int midTotal=0;
        int hardTotal=0;
        for (Integer t : totals) {
            if (0 < t && t < 30000)
                hardTotal++;
            else if (30000 < t && t < 300000)
                midTotal++;
            else if(t>300000)
                easyTotal++;
        }
        if(easyTotal==0)
            easyTotal=1;
        if(midTotal==0)
            midTotal=1;
        if(hardTotal==0)
            hardTotal=1;
        //不加1.0会丢失精度
        double easyRate=1.0*easy/easyTotal;
        double midRate=1.0*mid/midTotal;
        double hardRate=1.0*hard/hardTotal;
        double rate=easyRate*0.25+midRate*0.35+hardRate*0.45;
//        System.out.println(rate);
        int result=0;
        if(s>0&&s<360)
            result=(int)(10000*rate);
        else
            result=(int)(10000*rate+s*(-0.001));
        int i = historyService.addHistory(username, result,time);

        HashMap<String,Integer> resMap=new HashMap<>();
        if(i==1)
        {
            resMap.put("flag",1);
            resMap.put("res",result);
        }
        String data= JSON.toJSONString(resMap);
        return data;
    }


}
